<!-- 使用v-model将数据封到分页器中, 不用每次都写相同的逻辑 -->

<template>
  <el-pagination  class="u-my-pagination u-page"
    @size-change="handleSizeChange"
    @current-change="changePage"
    :current-page.sync="currentPage"
    :page-size="pageSize"
    layout="prev, pager, next, jumper"
    :total='total'>
  </el-pagination>
</template>

<script>
export default {
  name: 'my-pagination',
  model: {
    prop: 'list',
    event: 'change'
  },
  props: {
    // 分页数据
    list: {
      type: Array
    },
    // 获取分页数据API
    action: {
      type: Function
    },
    pageSize: {
      type: Number,
      default: 20
    }
  },
  data() {
    return {
      currentPage: 1,
      // 总个数
      total: 10
    }
  },

  methods: {
    changePage(page) {
      // 页数至少为1
      // 规定action传入(current, size)
      this.currentPage = page || this.currentPage || 1
      if (this.currentPage > Math.ceil(this.total / this.pageSize)) this.currentPage = Math.ceil(this.total / this.pageSize) || 1
      if (!this.action) {
        console.error('pagination no action error')
        return
      }
      return this.action(this.currentPage - 1, this.pageSize)
        .then(({ code, data }) => {
          if (code === 0) {
            this.total = parseInt(data.row_count || 0, 10)
            this.$emit('change', data.list || [])
          }
        })
    },

    setPage(page) {
      this.currentPage = page || 1
    },

    handleSizeChange() {}
  }
}
</script>

<style lang="less">
.u-page {
  margin: 15px 0;
}
</style>
